import re

from QQLoginTool.QQtool import OAuthQQ
from django import http
from django.conf import settings
from django.contrib.auth import login
from django.shortcuts import render, redirect

# Create your views here.
from django.views import View
from django_redis import get_redis_connection

from utils.myitsdangrous import encode_signature_openid, decode_signature_openid
from oauth.models import OAuthQQUser
from users.models import User


class QQAuthURLView(View):
    def get(self,request):
        #1.实例化一个oauth对象
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI,
                        )

        #2.通过oauth对象的 get_qq_url 方法获取一个二维码扫描地址
        login_url=oauth.get_qq_url()
        #重定向到二维码的地址
        return redirect(login_url)

class OauthCallBackView(View):
    def get(self,request):
        #1.初始化数据
        code=request.GET.get('code')
        if not code:
            return http.HttpResponseForbidden('code丢失了')
        #2.处理业务逻辑
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI,
                        )
        access_token=oauth.get_access_token(code)
        openid=oauth.get_open_id(access_token)

        #2.1查询是否绑定过
        try:
            oauth_user=OAuthQQUser.objects.get(openid=openid)
        except Exception as e:
            openid=encode_signature_openid(openid)
            return render(request,'oauth_callback.html',{'openid':openid})

        # #3.返回响应
        # #如果绑定过了就会直接跳到这里来
        # return http.HttpResponse(openid)

        #3.绑定过了，取用户user，返回响应
        user=oauth_user.user


        login(request,user)
        #返回响应
        response = redirect('/')
        response.set_cookie('username', user.username)

        return response

    def post(self,request):
        #处理用户绑定业务
        #1.初始化数据，手机号，密码，openid
        openid=request.POST.get('openid')
        mobile=request.POST.get('mobile')
        pwd=request.POST.get('pwd')
        sms_code=request.POST.get('sms_code')
        # pic_code=request.POST.get('pic_code').upper()



        if not all ([openid,mobile,pwd,sms_code]):
            return http.HttpResponseForbidden('参数不全')

        # 1,3 校验密码
        if not re.match(r'^[0-9A-Za-z]{8,20}$', pwd):
            return http.HttpResponseForbidden('密码格式有误')
        # 1,5 校验手机号
        if not re.match(r'^1[3-9]\d{9}$',mobile):
            return http.HttpResponseForbidden('手机号格式不正确')

        # redis_conn=get_redis_connection('verify_code')
        # redis_image_code=redis_conn.get('img_%s' %pic_code).decode()
        # print(redis_image_code)
        #
        # if pic_code != redis_image_code:
        #     return http.HttpResponseForbidden('图片验证码不正确')
        #
        #1,6 校验短信验证码
        redis_conn = get_redis_connection('verify_code')
        redis_sms_code = redis_conn.get('sms_%s' % mobile).decode()
        if sms_code != redis_sms_code:
            return http.HttpResponseForbidden('短信验证码错误')
        #1.7校验openid
        openid=decode_signature_openid(openid)
        if not openid:
            return http.HttpResponseForbidden('openid已经失效')

        #2.处理业务逻辑，绑定用户，并登录用户
        #2.1判断此手机号，是否已经注册美多用户
        #如果已经注册就直接绑定
        try:
            user=User.objects.get(mobile=mobile)
        except Exception as e:
            user=User.objects.create_user(username=mobile,password=pwd,mobile=mobile)
        #如果没有注册，就生成一个新用户，再绑定
        OAuthQQUser.objects.create(user=user,openid=openid)


        login(request,user)
        response=redirect('/')
        response.set_cookie('username',user.username)

        return response






















